package com.jinunn.yygh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinunn.yygh.listener.DictListener;
import com.jinunn.yygh.mapper.DictMapper;
import com.jinunn.yygh.service.DictService;
import com.jinunn.yygh.utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : JinDun
 * @date : 2021/4/24 22:49
 */

@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChileData(Long id) {
        List<Dict> dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", id));
        dictList.forEach(dict -> {
            Long dictId = dict.getId();
            boolean children = this.isChildren(dictId);
            dict.setHasChildren(children);
        });
        return dictList;
    }

    /**
     * 查询是否还有子节点
     * @param id 父节点id
     * @return true or false
     */
    private boolean isChildren(Long id){
        Integer count = baseMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id));
        return count>0;
    }


    @Override
    public void exportData(HttpServletResponse response) {
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
        int i=1;
        for (Dict dict:dictList){
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictEeVo.setNumber(i++);
            dictVoList.add(dictEeVo);
        }
        ExcelUtils.writeExcel(response,dictVoList,"数据字典","dict");
    }

    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper))
                    .sheet("dict").doRead();
        } catch (IOException e) {
            log.error("");
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isBlank(dictCode)) {
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value",value));
            return dict.getName();
        } else {
            //根据dictCode查询dict对象，得到dict的id
            Dict codeDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("dict_code", dictCode));

            // 根据parent_id和value查询dict对象
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", codeDict.getId())
                    .eq("value", value));
            return dict.getName();
        }
    }
}
